<!-- 广告管理 -->
<template>
  <div class="box_container">
    <!-- 输入框 -->
    <div class="box_input">
      <el-select v-model="pageinfo.status" placeholder="请选择广告状态">
        <el-option v-for="item in adStatusMap" :key="item.value" :label="item.name" :value="item.value">
        </el-option>
      </el-select>
      <el-select v-model="pageinfo.type" placeholder="请选择广告类型">
        <el-option v-for="item in adTypeMap" :key="item.value" :label="item.name" :value="item.value">
        </el-option>
      </el-select>
      <el-button icon="el-icon-search" type="primary" @click="onSeek">查找</el-button>
      <el-button icon="el-icon-plus" type="primary" @click="addAdmin">添加</el-button>
    </div>
    <!-- 广告管理列表 -->
    <div class="box_table">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="id" label="广告ID" align="center">
        </el-table-column>
        <el-table-column prop="title" label="广告标题" align="center">
        </el-table-column>
        <el-table-column label="广告图片" prop="imgUrl" align="center">
          <template #default="scope">
            <el-popover placement="right" width="300" trigger="hover" v-if="scope.row.type<5">
              <el-image style="width: 50px;" slot="reference" :src="scope.row.imgUrl"></el-image>
              <el-image style="width:100%;" :src="scope.row.imgUrl"></el-image>
            </el-popover>
            <el-tag type="info" v-else>此类型无需图片</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="广告类型" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.type===1">轮播</el-tag>
            <el-tag v-else-if="scope.row.type===2">分类精选</el-tag>
            <el-tag v-else-if="scope.row.type===3">横幅</el-tag>
            <el-tag v-else-if="scope.row.type===4">首页轮播下5按钮</el-tag>
            <el-tag v-else-if="scope.row.type===6">公告</el-tag>
            <el-tag v-else>商品下架</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="广告状态" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status==0?'success':'primary'"> {{scope.row.status == "0"? "冻结": "激活"}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="关联类型" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.unionType===1">商品</el-tag>
            <el-tag v-else-if="scope.row.unionType===2">类目</el-tag>
            <el-tag v-else-if="scope.row.unionType===3">关键字</el-tag>
            <el-tag v-else>功能页面</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="unionValue" label="关联[ID]" align="center">
        </el-table-column>
        <el-table-column prop="gmtCreate" label="创建时间" align="center">
          <template slot-scope="scope">
            {{new Date(scope.row.gmtCreate).format()}}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 添加--编辑弹框 -->
    <el-dialog :title="title" :visible.sync="dialogTableVisible">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="广告标题" prop="title">
          <el-input v-model="ruleForm.title" placeholder="请输入广告标题"></el-input>
        </el-form-item>
        <el-form-item label="广告类型" prop="type">
          <el-select v-model="ruleForm.type" placeholder="请选择" @change="changeType">
            <el-option v-for="item in adTypeMap" :key="item.value" :label="item.name" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item id="upload" :style="{background:ruleForm.color}" label="广告图片" prop="imgUrl" v-if="unionTypes.picRequire">
          <el-upload class=" avatar-uploader" :headers="headers" action="/upload/admin" list-type="picture-card" :show-file-list="false" :on-success="onSuccess" :before-upload="beforeUpload">
            <img v-if="ruleForm.imgUrl" :src="ruleForm.imgUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="广告状态" prop="status" style="margin-top: 30px;">
          <el-switch v-model="ruleForm.status" active-color="#13ce66" :active-value="1" :inactive-value="0">
          </el-switch>
        </el-form-item>
        <el-form-item label="关联类型" prop="unionType">
          <el-select v-model="ruleForm.unionType" placeholder="请选择" @change="changeUnionType">
            <el-option v-for="(item,index) in adUnionTypeMap" :key="item.value" :label="item.name" :value="item.value" :disabled="!types.includes(index+1)">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品" prop="unionValue" v-if="ruleForm.unionType==1">
          <el-cascader v-model="ruleForm.unionValue" :options="commodity" :props="cmmodityParams" clearable placeholder="请选择优惠类目"></el-cascader>
        </el-form-item>
        <el-form-item label="类目" prop="unionValue" v-if="ruleForm.unionType==2">
          <el-cascader v-model="ruleForm.unionValue" :options="options" :props="defaultParams" clearable placeholder="请选择优惠类目"></el-cascader>
        </el-form-item>
        <el-form-item label="关键字" prop="title" v-if="ruleForm.unionType==3">
          <el-input v-model="ruleForm.unionValue" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item label="功能页面" prop="unionValue" v-if="ruleForm.unionType==4">
          <el-select v-model="ruleForm.unionValue" placeholder="请选择功能页面">
            <el-option v-for="item in functionPages" :key="item.value" :label="item.name" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="display: flex;justify-content: end;">
          <el-button @click="dialogTableVisible=false"> 取消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 分页 --回到顶部 -->
    <div class="box_paging">
      <pagination :pageinfo="pageinfo" @change="changePage"></pagination>
    </div>
  </div>
</template>
<script>
import cookie from "js-cookie";
import Pagination from "../../components/pagination/MyPagination.vue"
import Apiadmin from "../../api/admin"
import { theColorFn } from "../../utils/backcolor" //使用canvas获取图片平均色
export default {
  components: { Pagination },
  data() {
    return {
      pageinfo: {
        limit: 10, //每页显示的数量
        page: 1,  //当前显示的页码
        total: 0, //数据总条数
        type: '', //广告类型
        status: '', //广告状态
      },
      tableData: [], //
      // 下拉框
      // 广告状态
      adStatusMap: [{
        value: 0,
        name: '冻结'
      },
      {
        value: 1,
        name: '激活'
      }],
      // 关联类型
      adUnionTypeMap: [{
        value: 1,
        name: '商品'
      }, {
        value: 2,
        name: '类目'
      },
      {
        value: 3,
        name: '关键字'
      },
      {
        value: 4,
        name: '功能页面'
      },],
      // 广告类型
      adTypeMap: [{
        value: 1,
        unionTypes: [1, 2, 3, 4],
        picRequire: true,   //上传图片弹框是否显示
        name: '轮播'
      }, {
        value: 2,
        unionTypes: [2],
        picRequire: true,
        name: '分类精选'
      }, {
        value: 3,
        unionTypes: [1, 2, 3, 4],
        picRequire: true,
        name: '横幅'
      },
      {
        value: 4,
        unionTypes: [1, 2, 3, 4],
        picRequire: true,
        name: '首页轮播下5按钮'
      },
      {
        value: 6,
        unionTypes: [1, 2, 3, 4],
        picRequire: false,
        name: '公告'
      },
      {
        value: 9,
        unionTypes: [1],
        picRequire: false,
        name: '商品推荐'
      },
      ],
      //功能页面
      functionPages: [{
        value: '/pages/product/groupshop',
        name: '团购列表'
      },
      {
        value: '/pages/coupon/list',
        name: '优惠券列表'
      }],
      headers: {
        AdminToken: cookie.get('AdminToken')
      },
      options: [], //优惠类目数据
      defaultParams: { // 级联选择器的配置
        checkStrictly: true, // 父子节点不互相关联
        label: 'title',  //渲染上去的名字
        value: 'id', //选中时的id
        children: 'childrenList',  //子节点数组
        emitPath: false // 只返回该节点的值
      },
      commodity: [], //商品类目数据
      cmmodityParams: { // 级联选择器的配置
        ocheckStrictly: true, // 父子节点不互相关联
        label: 'label',  //渲染上去的名字
        value: 'id', //选中时的id
        children: 'children',  //子节点数组
        emitPath: false // 只返回该节点的值
      },
      dialogTableVisible: false, //添加编辑弹框关闭
      title: '',  //添加编辑标题
      ruleForm: {
        type: '', //广告类型
        unionType: Number,//关联类型
        title: '',//广告标题
        unionValue: '',//关联值
        imgUrl: '',//广告图片地址
        status: 1,//广告状态
        color: '',//广告图片颜色
      },
      types: [], //选中时广告类型数组
      // 表单验证
      rules: {
        title: [
          { required: true, message: '请输入广告标题', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请输入广告类型', trigger: 'change' }
        ],
        // status: [
        //   { required: true, message: '请选择广告状态', trigger: 'blur' }
        // ],
        unionType: [
          { required: true, message: '请选择关联类型', trigger: 'change' },
        ],
        unionValue: [
          { required: true, message: '请选择关联值', trigger: 'blur' },
        ],
        imgUrl: [
          { required: true, message: '请上传图片', trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    this.operateList()
  },
  computed: {
    //记录当前advertisingType广告类型对应的类型对象
    unionTypes() {
      // 当广告类型更改时将关联类型初始化
      // this.ruleForm.unionType = '';
      let type = this.ruleForm.type
      if (!type) return false
      return this.getMatchObject(this.adTypeMap, type)
    }
  },
  methods: {
    // 检索对象
    getMatchObject(arr, value) {
      return arr.find(node => node.value == value)
    },
    // 请求广告管理数据
    operateList() {
      Apiadmin.advertList({ ...this.pageinfo, pageNo: this.pageinfo.page }).then(res => {
        // console.log(res)
        if (res.errno == 200) {
          this.tableData = res.data.items  //表格数据
          this.pageinfo.total = res.data.count  //分页总数据
        }
      })
      // 请求优惠类目数据
      Apiadmin.categoryTree().then(res => {
        // console.log(res)
        if (res.errno == 200) {
          this.options = res.data
        }
      })
      // 请求商品类目的数据
      Apiadmin.categoryTrees().then(res => {
        // console.log(res)
        if (res.errno == 200) {
          this.commodity = res.data
        }

      })
    },
    //查找广告管理用户
    onSeek() {
      this.pageinfo.page = 1, //查找页数重置为1
        // 请求数据时加载
        this.$showLoading(() => {
          this.operateList()
        })
    },
    //上传图片方法
    //成功时触发事件
    onSuccess(res) {
      // console.log(res)
      if (res.errno == 200) {
        this.ruleForm.imgUrl = res.url;  //上传图片成功的路径
        theColorFn(this.ruleForm.imgUrl, (callback) => {
          this.ruleForm.color = callback
        }) // 计算得到图片平均色
        this.operateList()
      }
    },

    //选择确定时触发
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('上传头像图片只能是JPG/PNG/JPEG格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isLt2M;
    },
    // 广告类型改变事件
    changeType(e) {
      // console.log(e)
      //获取广告类型对象
      this.adTypeMap.forEach(item => {
        if (item.value == e) {
          this.types = item.unionTypes
          this.ruleForm.unionType = ''  //关联重置
        }
      })
    },
    // 关联类型改变事件
    changeUnionType() {
      this.ruleForm.unionValue = ''   //关联重置
    },
    // 添加
    addAdmin() {
      this.title = '添加'
      this.dialogTableVisible = true  //弹框显示
      // this.ruleForm = {}   //清空表单
      // this.initObj(this.ruleForm, {})
      this.ruleForm = { unionType: '' }  //关联重置
      // 解决添加出现验证提示之后关闭弹出框,点击编辑发现验证信息还存在
      this.$nextTick(() => {
        this.resetForm("ruleForm")
      })
    },
    // 编辑
    handleEdit(row) {
      this.title = '编辑'
      this.dialogTableVisible = true  //弹框显示
      // 编辑时商品类目和优惠类目的关联值转换成数字类型
      if (!isNaN(row.unionValue)) {
        row.unionValue = parseInt(row.unionValue)
      }
      this.ruleForm = JSON.parse(JSON.stringify(row))
      // console.log(this.ruleForm)
      //获取广告类型对象
      this.adTypeMap.forEach(item => {
        if (item.value == row.type) {
          this.types = item.unionTypes
        }
      })
      //把默认的图片清除
      if (this.ruleForm.type > 5) {
        this.ruleForm.imgUrl = ''
      }
      // 解决编辑出现验证提示之后关闭弹出框,点击添加发现验证信息还存在
      this.$nextTick(() => {
        this.resetForm("ruleForm")
      })
    },
    //添加--编辑提交按钮
    submitForm(formName) {
      console.log(this.ruleForm)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 判断广告类型大于5时默认一张图片
          if (this.ruleForm.type > 5) {
            this.ruleForm.imgUrl = 'https://www.baidu.com/img/flexible/logo/pc/result.png'
          }
          if (this.title == '添加') {
            Apiadmin.advertAdd(this.ruleForm).then(res => {
              // console.log(res)
              if (res.errno == 200) {
                this.dialogTableVisible = false
                this.operateList() //刷新页面
                this.ruleForm = {} //清空表单
                this.$message({
                  message: '添加成功',
                  type: 'success'
                });
              } else {
                this.$message({
                  message: "添加失败",
                  type: 'error'
                });
              }
            }).catch(err => {
              console.log(err)
            })
          }
          if (this.title == '编辑') {
            Apiadmin.advertEdit({ ...this.ruleForm, adId: this.ruleForm.id }).then(res => {
              // console.log(res)
              if (res.errno == 200) {
                this.$message({
                  message: "编辑成功",
                  type: 'success'
                });
                this.dialogTableVisible = false
                this.operateList()  //刷新页面
                this.ruleForm = {}    //清空表单
              } else {
                this.$message({
                  message: "编辑失败",
                  type: 'error'
                });
              }
            })
          }

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //去除表单验证
    resetForm(formName) {
      //clearValidate方法为移除表单的校验结果          //resetFields(); //移除校验结果并重置字段值
      this.$refs[formName].clearValidate();          //clearValidate(); //移除校验结果
    },
    // 删除
    handleDelete(row) {
      Apiadmin.advertDelete({ type: row.type, adId: row.id }).then(res => {
        // console.log(res)
        if (res.errno == 200) {
          this.$confirm('此操作将永久删除, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(res => {
            this.operateList()   //刷新页面
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          }).catch(err => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          })
        }
      })
    },
    // 子组件传过来的方法和页长跟当前页
    changePage(e) {
      // console.log(e)
      this.pageinfo = JSON.parse(JSON.stringify(e))
      this.$nextTick(() => {
        this.operateList()
      })
    },

  }
}
</script>
<style scoped  lang="less">
</style>